'''
https://leetcode.cn/problems/longest-substring-with-at-most-two-distinct-characters/
'''
from collections import Counter


class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        n = len(s)
        cnt = Counter()
        l = r = 0
        n_cur_char = 0
        res = 0
        while r < n:
            cnt[s[r]] += 1
            if cnt[s[r]] == 1:
                n_cur_char += 1

            while n_cur_char > 2:
                cnt[s[l]] -= 1
                if cnt[s[l]] == 0:
                    n_cur_char -= 1
                l += 1
            res = max(res, r-l+1)
            r += 1
        return res



